
const encodeParam = function(param) {
    let a = []
    for (let key in param) {
        a.push(`${key}=${param[key]}`)
    }
    return a.join('&')
}

let ajax = function(options) {
    var xhr = new XMLHttpRequest();
    
    if (options.method.toUpperCase() === 'POST') {
        xhr.open(
            options.method,
            options.url,
            true
        )
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        // 发送请求
        xhr.send(encodeParam(options.data))
    } else if (options.method.toUpperCase() === 'GET') {
        xhr.open(
            options.method,
            options.url + '?'+encodeParam(param),
            true
        )
        xhr.send()
    }

    // 接受返回值
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status <= 300 || xhr.status === 304) {
                let res = xhr.response
                if (options.dataType === 'json') {
                    res = JSON.parse(res);
                }
                options.success && options.success(res)
            } else {
                options.error && options.error(xhr.response)
            }
        }
    }
}